import os
import re
from decimal import Decimal, ROUND_HALF_UP
from typing import Union

import cv2
import numpy as np
import pymysql
import redis
import win32gui
from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=False, lang='ch')

def find_window_position_and_check_foreground(window_title_keyword):
    """

    :rtype: Union[tuple[int, int, int, int, bool], tuple[Any, Any, Any, Any, bool]]
    """
    def enum_handler(hwnd, result_list):
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            if window_title_keyword in title:
                rect = win32gui.GetWindowRect(hwnd)
                result_list.append((hwnd, title, rect))

    windows = []
    win32gui.EnumWindows(enum_handler, windows)

    if not windows:
        print(f"未找到窗口包含 '{window_title_keyword}' 的应用")
        return -1, -1, -1, -1, False
    foreground_hwnd = win32gui.GetForegroundWindow()
    for hwnd, title, rect in windows:
        x, y = rect[0], rect[1]
        width, height = rect[2] - rect[0], rect[3] - rect[1]
        is_foreground = (hwnd == foreground_hwnd)
        print(f"找到窗口: {title}")
        print(f"x={x}, y={y}, width={width}, height={height}")
        if is_foreground:
            print("该窗口当前在前台")
        else:
            print("该窗口当前不在前台")
            is_foreground = False
        return x, y, width, height, is_foreground
    return -1, -1, -1, -1, False


def screenshot(x,y,width,height,filename):
    print(f"<截图>{x},{y},{width},{height}")
    screen = pyautogui.screenshot(region=(x, y, width, height))
    screen.save(filename+".png")


def getTextPosition(content, x, y, width, height):
    print(x,y,width,height)
    start_time = time.perf_counter()
    # 截图并保存调试图
    screen = pyautogui.screenshot(region=(x, y, width, height))
    img_np = np.array(screen)
    image = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
    cv2.imwrite("debug_capture.jpg", image)  # 保存调试图像

    result = ocr.predict(image)
    for block in result:
        texts = block.get("rec_texts", [])
        boxes = block.get("rec_boxes", [])
        for text, box in zip(texts, boxes):
            if content in text:
                x1, y1, x3, y3 = box
                width = x3 - x1
                height = y3 - y1
                end_time = time.perf_counter()
                print(f"[✔] 找到目标文本 '{content}'，坐标: ({x1}, {y1}), 宽度: {width}, 高度: {height}; 耗时：{end_time - start_time:.2f}秒")
                return int(x1), int(y1), int(width), int(height), True

    end_time = time.perf_counter()
    print(
        f"[✘] 未找到目标文本 '{content}'，耗时：{end_time - start_time:.2f}秒")
    return -1, -1, -1, -1, False

def parseInfo(x, y, width, height,filename):
    start_time = time.perf_counter()
    # 截图并保存调试图
    screen = pyautogui.screenshot(region=(x, y, width, height))
    img_np = np.array(screen)
    image = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
    cv2.imwrite(filename, image)  # 保存调试图像
    result = ocr.predict(image)
    texts = []
    for item in result:
        if 'rec_texts' in item:
            texts.extend(item['rec_texts'])
    end_time = time.perf_counter()
    print(
        f"[✔] 文本解析完成：{texts}; 耗时：{end_time - start_time:.2f}秒")
    return texts


def click(text,x,y):
    print(f"点击{text}位置：{x,y}")
    pyautogui.moveTo(x, y)
    pyautogui.click(x,y)

from PIL import Image
import win32clipboard
import win32con
import io
def copy_image_to_clipboard(image_path):
    image = Image.open(image_path).convert("RGB")

    # 保存到内存缓冲区为 BMP 格式（去掉 BMP 文件头）
    output = io.BytesIO()
    image.save(output, 'BMP')
    data = output.getvalue()[14:]  # 跳过 BMP 文件头
    output.close()

    # 设置剪贴板数据
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(win32con.CF_DIB, data)
    win32clipboard.CloseClipboard()

def send_image(image_path):
    copy_image_to_clipboard(image_path)
    pyautogui.hotkey('ctrl', 'v')  # 粘贴
    time.sleep(0.3)
    pyautogui.press('enter')

import pyautogui
import pyperclip
import time
def send_text(message):
    # 1. 选中输入框内容并清空（模拟 Ctrl+A，然后 Delete）
    pyautogui.hotkey('ctrl', 'a')  # 全选
    time.sleep(0.1)
    pyautogui.press('backspace')  # 删除
    time.sleep(0.1)
    # 2. 复制你要发送的内容到剪贴板
    pyperclip.copy(message)

    # 3. 粘贴并发送
    pyautogui.hotkey('ctrl', 'v')  # 粘贴
    time.sleep(0.2)
    pyautogui.press('enter')

def initRedis():
    return redis.Redis(
        host='r-bp1qc1brulm4ztx0egpd.redis.rds.aliyuncs.com',
        port=6379,
        username="weiyi0601",
        password="weiyi0601@!@#",
        db=0,
        decode_responses=True
    )

DB_CONFIG = {
    'host': 'rm-bp15i0p5o0n8p3gu2uo.mysql.rds.aliyuncs.com',
    'port': 3306,
    'user': 'igomall',
    'password': 'igomall@123456',
    'database': 'ai_learn',
    'charset': 'utf8mb4'
}

def check(image_path,bitType):
    if not os.path.exists(image_path):
        print(f"文件不存在: {image_path}")
        return []
    result = ocr.predict(image_path)
    rec_texts = result[0]['rec_texts']
    print(rec_texts)
    money_re = re.compile(r'(?:￥|¥)?\s*(\d+(?:\.\d+)?)\s*元?')

    def parse_amount(s: str):
        m = money_re.search(s)
        return Decimal(m.group(1)) if m else None

    def odd_even_flag(amount) -> int:
        """
        计算金额小数点后两位数字之和，返回奇偶标记：
        奇数 -> 1
        偶数 -> 0
        """
        if amount is None:
            return None
        amt = Decimal(str(amount)).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
        cents = int((amt * 100).to_integral_value())  # 转换成整数分
        d1 = (cents // 10) % 10  # 角
        d2 = cents % 10  # 分
        return 1 if ((d1 + d2) % 2 == 1) else 0

    amount_positions = [(i, parse_amount(txt)) for i, txt in enumerate(rec_texts)]
    amount_positions = [(i, amt) if amt is not None else None for i, amt in amount_positions]
    amount_positions = [x for x in amount_positions if x is not None]

    grab_amount = amount_positions[0][1] if amount_positions else None
    if grab_amount > 10:
        grab_amount = grab_amount / 100
    result = odd_even_flag(grab_amount)
    print(f"单双：{grab_amount}：{result}")
    conn = pymysql.connect(**DB_CONFIG)
    try:
        with conn.cursor() as cursor:
            sql = "SELECT id FROM redpackageinfo ORDER BY sn DESC LIMIT 1"
            cursor.execute(sql)
            last_record = cursor.fetchone()
            # 判断是否存在记录
            if last_record:
                sql = "UPDATE redpackageinfo SET win=%s,money=%s,version=version+1,lastModifiedDate=NOW() WHERE id=%s"
                if result == bitType:
                    cursor.execute(sql,(True,grab_amount,last_record[0]))
                else:
                    cursor.execute(sql, (False,grab_amount, last_record[0]))
                conn.commit()
            else:
                print("没有找到记录，不执行下一步")
    except Exception as e:
        print(e)
    finally:
        conn.close()

def saveLotteryRecord(betResult,betType,lotteryCode,money,num,sn):
    conn = pymysql.connect(**DB_CONFIG)
    try:
        with conn.cursor() as cursor:
            sql = "insert into betrecord(createdDate, lastModifiedDate, version, betResult, betType, lotteryCode, money, num, sn) values (NOW(),NOW(),0,%s,%s,%s,%s,%s,%s) on duplicate key update version=version+1,lastModifiedDate=NOW()"
            cursor.execute(sql, (betResult, betType, lotteryCode, money, num, sn))
            conn.commit()
    except Exception as e:
        print(e)
    finally:
        conn.close()

if __name__ == "__main__":
    check(r"C:\Users\36787\PycharmProjects\PythonProject\wallet.png")